<script setup lang="ts">
import { ref, reactive } from "vue";
// 计算属性就是当依赖的属性的值发生变化的时候，才会触发他的更改，如果依赖的值，不发生变化的时候，使用的是缓存中的属性值。
import { computed } from "vue";
//  计算属性监听基本数据类型
let count = ref(0);
let countComputed = computed(() => {
  return count.value + 2;
});
const changeCount = () => {
  count.value++;
};
//  对象类型
let person = reactive({ name: "张三", age: 19 });
let personAge = computed(() => {
  return ++person.age;
});
const changePersonAge = () => {
  person.age++;
};

//  对象属性
let num = ref(100);
let numComputed = computed({
  get: () => {
    return num.value;
  },
  set: (value) => {
    num.value = value;
  },
});
// ##################################################################
type Shop = {
  name: string;
  num: number;
  price: number;
};
const data = reactive([
  { name: "上衣", num: 1, price: 100 },
  { name: "裤子", num: 2, price: 200 },
  { name: "鞋子", num: 3, price: 300 },
]);
const addAndSub = (item: Shop, addType: boolean = false): void => {
  if (item.num < 100 && addType) {
    item.num++;
  }
  if (item.num > 1 && !addType) {
    item.num--;
  }
};
const del = (index: number): void => {
  console.log(index, index);

  data.splice(index, 1);
};
let $total = computed<number>(() => {
  return data.reduce((pre, next) => {
    return pre + next.num * next.price;
  }, 0);
});
</script>
<template>
  <div>
    count：{{ count }}================countComputed：{{ countComputed }}
  </div>
  <div><button @click="changeCount">修改count</button></div>
  <div>person{{ person }}================personAge{{ personAge }}</div>
  <div><button @click="changePersonAge">修改PersonAge</button></div>
  <div>num{{ num }}================numComputed{{ numComputed }}</div>
  <div><button @click="numComputed += 200">修改numComputed</button></div>
  <hr />
  <table border>
    <tr>
      <td>名称</td>
      <td>数量</td>
      <td>价格</td>
      <td>操作</td>
    </tr>
    <tr v-for="(item, index) in data" :key="index">
      <td>{{ item.name }}</td>
      <td>
        <button @click="addAndSub(item, false)">-</button>
        {{ item.num }}
        <button @click="addAndSub(item, true)">+</button>
      </td>
      <td>{{ item.price }}</td>
      <td>
        <button @click="del(index)">删除</button>
      </td>
    </tr>
    <tr>
      <td></td>
      <td></td>
      <td></td>
      <td>总价{{ $total }}</td>
    </tr>
  </table>
</template>
